package org.linlinjava.litemall.admin.service;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.linlinjava.litemall.admin.beans.vo.PointExchangeLogVo;
import org.linlinjava.litemall.admin.beans.vo.PointExchangeRespVO;
import org.linlinjava.litemall.admin.beans.vo.PointExchangeStatisticVo;
import org.linlinjava.litemall.admin.controller.pointexchange.vo.LumierePointExchangePageReqVO;
import org.linlinjava.litemall.admin.vo.pointexchange.PointExchangeStatisticReqVO;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LumierePointExchangeMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理卢米埃点交换服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Service
public class AdminLumierePointExchangeService {

    /**
     * 卢米埃点交换服务
     */
    @Autowired
    private LumierePointExchangeService lumierePointExchangeService;

    /**
     * litemall订单服务
     */
    @Autowired
    private LitemallOrderService litemallOrderService;

    /**
     * litemall订货服务
     */
    @Autowired
    private LitemallOrderGoodsService litemallOrderGoodsService;

    @Autowired
    private LitemallOrderPackageService litemallOrderPackageService;

    /**
     * litemall订货房地产服务
     */
    @Autowired
    private LitemallOrderGoodsPropertyService litemallOrderGoodsPropertyService;

    /**
     * litemall订货配件服务
     */
    @Autowired
    private LitemallOrderGoodsAccessoryService litemallOrderGoodsAccessoryService;

    /**
     * litemall用户服务
     */
    @Autowired
    private LitemallUserService litemallUserService;

    /**
     * litemall店服务
     */
    @Autowired
    private LitemallShopService litemallShopService;

    /**
     * litemall类别服务
     */
    @Autowired
    private LitemallCategoryService litemallCategoryService;

    @Autowired
    private LitemallGoodsService litemallGoodsService;

    /**
     * 添加
     * 添加积分兑换
     *
     * @param lumierePointExchange 卢米埃点交流
     * @return {@link Object}
     */
    public Object add(LumierePointExchange lumierePointExchange){
        lumierePointExchangeService.add(lumierePointExchange);
       return ResponseUtil.ok("积分兑换添加成功");
    }

    /**
     * 更新
     * 编辑积分兑换
     *
     * @param lumierePointExchange 卢米埃点交流
     * @return {@link Object}
     */
    public Object update(LumierePointExchange lumierePointExchange){
        lumierePointExchangeService.update(lumierePointExchange);
        return ResponseUtil.ok("积分兑换修改成功");
    }

    /**
     * 删除
     *
     * @param pointExchangeId 点交易id
     * @return {@link Object}
     */
    public Object delete(Integer pointExchangeId){
        lumierePointExchangeService.delete(pointExchangeId);
        return ResponseUtil.ok("积分兑换删除成功");
    }


    public Object totalStatistic(PointExchangeStatisticReqVO reqVO){
        LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper();
        orderLambdaQueryWrapper.isNotNull(LitemallOrder::getExId);

        orderLambdaQueryWrapper.eq(reqVO.getPointExchangeId()!=null,LitemallOrder::getExId,reqVO.getPointExchangeId());
        orderLambdaQueryWrapper.eq(reqVO.getShopId()!=null,LitemallOrder::getShopId,reqVO.getShopId());
        orderLambdaQueryWrapper.eq(reqVO.getOrderSource()!=null,LitemallOrder::getOrderSource,reqVO.getOrderSource());
        // 添加时间范围过滤
        if (CollUtil.isNotEmpty(reqVO.getDateTime())) {
            orderLambdaQueryWrapper.between(LitemallOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
        }
        orderLambdaQueryWrapper.orderByDesc(LitemallOrder::getAddTime);
          IPage<LitemallOrder> orders = litemallOrderService.page(new Page<>(reqVO.getPage(), reqVO.getLimit()),orderLambdaQueryWrapper);
          PointExchangeStatisticVo vo = new PointExchangeStatisticVo();

          //兑换次数
          vo.setExchangeNum(orders.getRecords().size());

          //总兑换积分
          BigDecimal point = BigDecimal.ZERO;
          BigDecimal price = BigDecimal.ZERO;
          Integer goodsNum = 0;
            for (int i = 0; i < orders.getRecords().size(); i++) {

                if(orders.getRecords().get(i).getPoints() != null){
                    point = point.add(orders.getRecords().get(i).getPoints());
                }

                if(orders.getRecords().get(i).getGoodsPrice() != null){
                    price = price.add(orders.getRecords().get(i).getGoodsPrice());

                    if(CollUtil.isNotEmpty(orders.getRecords().get(i).getOrderGoods())){
                        List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.getOrderGoodsByIds(orders.getRecords().get(i).getGoodsIds());
                        goodsNum+=orderGoodsList.stream()
                                .mapToInt(LitemallOrderGoods::getNumber)
                                .sum();
                    }
                    if(CollUtil.isNotEmpty(orders.getRecords().get(i).getPackageIds())){
                        List<LitemallOrderPackage> orderPackageList = litemallOrderPackageService.listByIds(orders.getRecords().get(i).getPackageIds());
                        goodsNum+=orderPackageList.stream()
                                .mapToInt(LitemallOrderPackage::getNumber)
                                .sum();
                    }

                }
            }
          vo.setGoodsNum(goodsNum);
          vo.setPoint(point);
          vo.setPrice(price);
       return ResponseUtil.ok(vo);
    }


    public Object typeTotalStatistic(PointExchangeStatisticReqVO reqVO){

        LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper();
        orderLambdaQueryWrapper.isNotNull(LitemallOrder::getExId);
        orderLambdaQueryWrapper.eq(reqVO.getPointExchangeId()!=null,LitemallOrder::getExId,reqVO.getPointExchangeId());
        orderLambdaQueryWrapper.eq(reqVO.getShopId()!=null,LitemallOrder::getShopId,reqVO.getShopId());
        orderLambdaQueryWrapper.eq(reqVO.getOrderSource()!=null,LitemallOrder::getOrderSource,reqVO.getOrderSource());
        // 添加时间范围过滤
        if (CollUtil.isNotEmpty(reqVO.getDateTime())) {
            orderLambdaQueryWrapper.between(LitemallOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
        }
        orderLambdaQueryWrapper.orderByDesc(LitemallOrder::getAddTime);
        IPage<LitemallOrder> orders = litemallOrderService.page(new Page<>(reqVO.getPage(), reqVO.getLimit()),orderLambdaQueryWrapper);
        Integer total = orders.getRecords().size();
        Map<Integer,List<LitemallOrder>> map =  orders.getRecords().stream().filter(litemallOrder->litemallOrder.getExId()!=null).collect(Collectors.groupingBy(LitemallOrder::getExId));

        List<Integer> goodsList = new ArrayList<>();
        if(reqVO.getGoodsId()!=null){
            goodsList.add(reqVO.getGoodsId());
        }

        if(reqVO.getCategoryl3()!=null){
            List<LitemallGoods> litemallGoods = litemallGoodsService.queryByCategoryAll(reqVO.getCategoryl3());
            goodsList.addAll(CollStreamUtil.toList(litemallGoods,LitemallGoods::getId));
        }


        List  vos = new ArrayList<>();

        map.keySet().forEach(key -> {
            LumierePointExchange exchange =   lumierePointExchangeService.findById(key);
            PointExchangeStatisticVo vo = new PointExchangeStatisticVo();
            if(exchange != null){
                vo.setPointExchangeName(exchange.getName());
            }

            List<LitemallOrder> os = map.get(key);
            //积分
            BigDecimal point = BigDecimal.ZERO;
            BigDecimal price = BigDecimal.ZERO;
            Integer goodsNum = 0;
            for (int i = 0; i < os.size(); i++) {
                if(os.get(i).getPoints() != null){
                    point = point.add(os.get(i).getPoints());
                }

                if(os.get(i).getGoodsPrice() != null){
                    price = price.add(os.get(i).getGoodsPrice());

                    if(orders.getRecords().get(i).getOrderGoods().size()>0){
                        // 获取当前订单的商品ID列表
                        List<Integer> orderGoodsIds = orders.getRecords().get(i).getGoodsIds();

                        // 过滤出与 goodsList 相互包含的商品ID
                        List<Integer> filteredGoodsIds = orderGoodsIds.stream()
                                .filter(goodsList::contains)
                                .collect(Collectors.toList());

                        // 如果有交集，则查询这些ID对应的商品
                        if(CollUtil.isNotEmpty(filteredGoodsIds)){
                            List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.getOrderGoodsByIds(filteredGoodsIds);
                            goodsNum += orderGoodsList.stream()
                                    .mapToInt(LitemallOrderGoods::getNumber)
                                    .sum();
                        }
                    }
                    if(orders.getRecords().get(i).getPackageIds().size()>0){
                        List<LitemallOrderPackage> orderPackageList = litemallOrderPackageService.listByIds(orders.getRecords().get(i).getPackageIds());
                        goodsNum+=orderPackageList.stream()
                                .mapToInt(LitemallOrderPackage::getNumber)
                                .sum();
                    }
                }

            }
            vo.setGoodsNum(goodsNum);
            vo.setPoint(point);
            vo.setPrice(price);


            double d1 = os.size() * 1.0;
            double d2 = total * 1.0;
            // 设置保留几位小数， “.”后面几个零就保留几位小数，这里设置保留四位小数
            DecimalFormat decimalFormat = new DecimalFormat("##.00%");


            vo.setExchangePer( decimalFormat.format(d1 / d2));

            vo.setExchangeNum(os.size());

            vo.setExchangeId(exchange.getId());

            vos.add(vo);
        });
        orders.setRecords(vos);
       return ResponseUtil.okPage(orders);
    }

    /**
     * 由点交换日志
     *
     * @param pointExchangeId 点交易id
     * @param goodsName       商品名称
     * @param userName        用户名
     * @param exchangeTime    交换时间
     * @param shopId          商店id
     * @param sort            排序
     * @param ord             奥德
     * @param page            页面
     * @param size            大小
     * @return {@link Object}
     */
    public Object logByPointExchange(Integer pointExchangeId,String goodsName,
                                     String userName,String exchangeTime,Integer shopId,String sort,String ord,Integer page,Integer size){
      IPage<LitemallOrder> orders =   litemallOrderService.queryByExchangeId(pointExchangeId,sort,ord,page,size);
      List<PointExchangeLogVo> logs = orders.getRecords().stream().map(order ->{
          PointExchangeLogVo vo = new PointExchangeLogVo();

          boolean flag = true;

            //查询商品
            LitemallOrderGoods goods = litemallOrderGoodsService.queryByOid(order.getId()).get(0);

            List<LitemallOrderGoodsProperty> properties = litemallOrderGoodsPropertyService.queryByOrderId(order.getId());

            List<LitemallOrderGoodsAccessory> accessories = litemallOrderGoodsAccessoryService.findByOrderId(order.getId());


            String specifications = goods.getSpecifications()[0] +" ";



           if(goodsName != null && goods.getGoodsName().indexOf(goodsName) == -1){
               flag = false;
           }

            vo.setGoodsName(goods.getGoodsName());
            vo.setSpecificationsName(specifications);
            vo.setProperties(properties);
            vo.setAccessories(accessories);

            //积分兑换
            LumierePointExchange exchange = lumierePointExchangeService.findById(order.getExId());
            vo.setPointExchangeName(exchange.getName());

            //门店
            if(order.getShopId() != null){
               LitemallShop shop =  litemallShopService.findById(order.getShopId());
               vo.setShopName(shop.getName());
            }else{
                vo.setShopName(null);
            }

          if(shopId != null && order.getShopId() != shopId){
              flag = false;
          }

            //价格
           vo.setGoodsPrice(order.getGoodsPrice());
            vo.setPoints(order.getPoints());

            //会员名称
          if(order.getUserId() != null){
              LitemallUser user = litemallUserService.findById(order.getUserId());
              if(user != null){
                  vo.setUserName(user.getUsername());
              }

              if(userName != null && user.getUsername().indexOf(userName) == -1){
                  flag = false;
              }
          }

          DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
          String exTime = df.format(order.getAddTime());
          if(exchangeTime != null && exTime.equals(exchangeTime) == false){
              flag = false;
          }
          vo.setExchangeTime(exTime);

          if(flag != false){
              return vo;
          }else{
              return null;
          }

      }).collect(Collectors.toList());

      logs = logs.stream().filter( log -> {
          if(log == null){
              return false;
          }else{
              return true;
          }
      }).collect(Collectors.toList());
        List  logs1 = logs;
        orders.setRecords(logs1);
       return ResponseUtil.okPage(orders);
    }

    /**
     * 发现通过id
     *
     * @param pointExchangeId 点交易id
     * @return {@link LumierePointExchange}
     */
    public LumierePointExchange findById(Integer pointExchangeId){
        return lumierePointExchangeService.findById(pointExchangeId);
    }


    public Object list(LumierePointExchangePageReqVO respVO){
        Page<LumierePointExchange> pointExchangePage = lumierePointExchangeService.selectPage(respVO.getPointExchangeName(), respVO.getPage(), respVO.getLimit());
        Page<PointExchangeRespVO> pointExchangeRespPage = BeanUtil.copyPage(pointExchangePage, PointExchangeRespVO.class);
        pointExchangeRespPage.getRecords().forEach(item->{
            item.setMoneyRange(item.getMinMoney() + "--" + item.getMaxMoney());
            List<LitemallCategory> categoryHierarchy = litemallCategoryService.findCategoryHierarchy(item.getCategoryIds().get(0));
            // 通过流遍历并提取分类名称（去除最后一个元素）
            String categoryPath = categoryHierarchy.stream()
                    .limit(categoryHierarchy.size() - 1)
                    .map(LitemallCategory::getName)
                    .collect(Collectors.joining(" / "));
            List<LitemallCategory> categoryList = litemallCategoryService.findByIds(item.getCategoryIds());
            item.setGoodsCategory(categoryPath);
            item.setCategoryList(categoryList);
        });
        return ResponseUtil.okPage(pointExchangeRespPage);
    }

    /**
     * 按名称查询
     *
     * @param name 名字
     * @return {@link List}<{@link LumierePointExchange}>
     */
    public List<LumierePointExchange> queryByName(String name){
        return lumierePointExchangeService.queryByName(name);
    }

    /**
     * 连接商品类别
     * 关于商品分类名称的递归
     *
     * @param categoryId    类别id
     * @param goodsCategory 商品类别
     * @return {@link String}
     */
    public String connectGoodsCategory(Integer categoryId,String goodsCategory){
        LitemallCategory categoryLv =  litemallCategoryService.findById(categoryId);

        if(categoryLv != null){
             goodsCategory += categoryLv.getName();
             //递归寻找父级分类
             if(categoryLv.getPid() != 0){
                 goodsCategory += ",";
                 goodsCategory =  connectGoodsCategory(categoryLv.getPid(),goodsCategory);
             }
             return goodsCategory;
        }else{
            return null;
        }
    }

    /**
     * 商品类别id列表
     *
     * @param categoryId      类别id
     * @param listCategoryIds 类别id列表
     * @return {@link List}<{@link Integer}>
     */
    public List<Integer> listGoodsCategoryIds(Integer categoryId,List<Integer> listCategoryIds){
        LitemallCategory category = litemallCategoryService.findById(categoryId);

        if(category != null){
            listCategoryIds.add(category.getId());

            List<LitemallCategory> categories =  litemallCategoryService.queryByPid(category.getId());

            for (int i = 0; i < categories.size(); i++) {
                listCategoryIds.add(categories.get(i).getId());

                listCategoryIds =  listGoodsCategoryIds(categories.get(i).getId(),listCategoryIds);
            }


        }
        return listCategoryIds;
    }


    public Object listAllPointExchange() {
        List<LumierePointExchange> exchanges = lumierePointExchangeService.queryAll();
        return ResponseUtil.ok(exchanges);
    }
}
